<script>
var url = "http://dbimg.u.qiniudn.com/audio/demo.mp3";
var source = null;
var context = new AudioContext();
var gain = null;
var f = null;
var _m = false;
var ana = null;
var dataArray = null;
var ctx = document.querySelector("#v").getContext('2d');
var vid = null;
var f = null;
function calcRgb(value){
  var v = 255;
  if(value>=128){
    v = parseInt(((value - 128) / 128) * 255)
  }
  var arr = [255,v,0];
  return "rgb("+arr.join(",")+")";
}


function drawLine(idx,value){


  ctx.beginPath();

  ctx.strokeStyle = "green";//calcRgb(value);

  ctx.moveTo(idx,500);
  ctx.lineTo(idx,value)
  // ctx.arc(240, 240, (idx+1)*7, 0,2*Math.PI);
  ctx.stroke();
  // ctx.save();
}
var tm = 0;
function draw(){
  ctx.clearRect(0, 0, 1024,500);
  ana.getByteTimeDomainData(dataArray);

  // var dd = [];
  for(var i=0;i<1024;i++){
    // dd.push(dataArray[i*32]);
    drawLine(i,dataArray[i]);
  }

  // if(tm<dataArray[500]){
  //   tm = dataArray[500];
  //   console.log(tm);
  // }
  
  // console.clear();
  // console.log(dd.join(" "));
  vid = requestAnimationFrame(draw);
}


function play(url){
  
  var _buff = null;
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'arraybuffer';
  request.onload = function () {
    context.decodeAudioData(request.response, function (b) {
      console.info('play...')
      source = context.createBufferSource();
      source.buffer = b;
      ana = context.createAnalyser();
      f = context.createBiquadFilter();
      source.connect(f);
      f.connect(ana);
      ana.fftSize = 2048;
      var bufferLength = ana.frequencyBinCount;
      dataArray = new Uint8Array(bufferLength);
      ana.connect(context.destination);
      source.start();

      draw();

    }, function(e){
      console.log(e);
    });
  }
  request.send();  

}
